//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by Tony-ztb on 15/12/25.
//  Copyright © 2015年 Tony-ztb. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    // 响应方法 一般写在最上面 显眼的地方
    
//    var textViewBottomConstraints: Constraint?
    
    // toolBar 添加图片按钮点击事件
    @objc private func selectPicture() {
        print(__FUNCTION__)
        
        // 隐藏键盘
        textView.resignFirstResponder()
        
        
        
        let pictureSelectH: CGFloat = screenH * 2 / 3
        pictureSelect.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(pictureSelectH)
        }
        
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // toolBar 添加表情按钮点击事件
    @objc private func selectEmoticonKeyboard() {
        print(__FUNCTION__)
    }
    
    // 关闭评论界面
    @objc private func cancleCompose() {

        dismissViewControllerAnimated(true, completion: nil)
    }
    // 发送按钮点击事件
    @objc private func sendCompose() {
        
        var urlString = "2/statuses/update.json"
        
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showInfoWithStatus("检查网络, 请重新登录", maskType: .Gradient)
            return
        }
        
        let parameters = ["access_token": token, "status": textView.text ?? ""]
        
        
        if pictureSelect.imageList.count != 0 {
            // 上传图片
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let imageData = UIImagePNGRepresentation(pictureSelect.imageList.first!)
            NetworkTools.sharedTools.uploadImage(urlString, parameters: parameters, imageData: imageData!, finished: { (dict, error) -> () in
                self.finishedUpdateStatus(dict, error: error)
            })
        } else {
            
            NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                self.finishedUpdateStatus(dict, error: error)
            }
        }
    }
    
    private func finishedUpdateStatus(dict: [String : AnyObject]?, error: NSError?) {
        if error != nil {
            SVProgressHUD.showInfoWithStatus("发布微博失败, 请检查网络", maskType: .Gradient)
            return
        }
        
        SVProgressHUD.showInfoWithStatus("已发布", maskType: .Black)
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        // 设置UI
        setupUI()
        
       
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureSelect.imageList.count == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    
    
    
    // MARK: - 懒加载子视图
    private lazy var textView: UITextView = {
        
        let textV = UITextView()
        
        textV.font = UIFont.systemFontOfSize(18)
        textV.backgroundColor = UIColor.whiteColor()
        // 垂直滚动开启
        textV.alwaysBounceVertical = true
        // 滚动的时候, 键盘失去响应
        textV.keyboardDismissMode = .OnDrag
        
        textV.delegate = self
        
        return textV
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", color: UIColor.lightGrayColor(), fontSize: 18)
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var pictureSelect: PictureSelectViewController = PictureSelectViewController()
    
    // 析构函数
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK: - UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
    // 监测文本的改变
    func textViewDidChange(textView: UITextView) {
        // 根据textView是否有文本, 隐藏占位文本, 开启发送按钮的交互
        placeHolderLabel.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}


extension ComposeViewController {

    private func setupUI() {
        
        setNavBar()
        setToolBar()
        setTextView()
        setPictureSelect()
        
        // 注册键盘响应通知
        registerNotification()
    }
    
    // MARK: - 键盘通知监听事件
    @objc private func keyboardWillChange(n: NSNotification) {
//        print(n)
        
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offsetY = -screenH + endRect.origin.y
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    // MARK: - 注册键盘响应通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    
    // MARK: - 设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancleCompose")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendCompose")
        // 默认发送按钮不可点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        // 自定义titleView
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        // 添加Label
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    
    
    // MARK: - 设置输入框视图
    private func setTextView() {
        // 添加textView
        view.addSubview(textView)
        
        // 设置约束
//        textView.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(self.view)
//        }
        
        textView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(self.view)
            make.bottom.equalTo(toolBar.snp_top)
            
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    // MARK: - 设置ToolBar
    private func setToolBar() {
        /**
         自定义一个toolBar数组, 遍历按钮添加到数组中
         */
         // 创建一个数组
        var items = [UIBarButtonItem]()
        // 给数组中添加元素
        let itemSetting = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSetting {
            let itemImageName = item["imageName"]
            let itemBtn = UIButton(imageName: nil, backImageName: itemImageName!)
            
            if let action = item["actionName"] {
                // 按钮对应的点击响应事件
                itemBtn.addTarget(self, action: Selector(action) , forControlEvents: .TouchUpInside)
            }
            
            let barButtonItem = UIBarButtonItem(customView: itemBtn)
            // 添加到数组中
            items.append(barButtonItem)
            // 添加弹簧
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(flexibleSpace)
        }
        // 移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
        // 添加到父视图
        view.addSubview(toolBar)
        
        // 设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            
        }
    }
    
    // MARK: - 设置PictureSelect
    private func setPictureSelect() {
        // 添加视图控制器
        addChildViewController(pictureSelect)
        // 添加视图控制器的根视图
        view.addSubview(pictureSelect.view)
        // 将toolBar一道视图顶层
        view.bringSubviewToFront(toolBar)
        // 添加约束
        pictureSelect.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            
            make.height.equalTo(0)
        }
        
    }
    
    
    
}


